package com.example.zhu.controller;

import com.example.zhu.entity.Coupon;
import com.example.zhu.result.Result;
import com.example.zhu.service.CouponService;
import com.example.zhu.vo.CouponVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;


@RestController
@Slf4j
@RequestMapping("/coupon")
@CrossOrigin
public class CouponController {

    @Autowired
    private CouponService couponService;

    /**
     * 根据名称查询优惠券
     * @return
     */
    @GetMapping("/getByName")
    public Result<List<CouponVO>> getByName(@RequestParam String name){
        List<Coupon> couponList = couponService.selectByName(name);
        List<CouponVO> couponVOList = new ArrayList<>();
        process(couponList, couponVOList);
        return Result.success(couponVOList);
    }

    /**
     * 查询全部优惠券
     * @return
     */
    @GetMapping
    public Result<List<CouponVO>> getAll(){
        List<Coupon> couponList = couponService.selectAll();
        List<CouponVO> couponVOList = new ArrayList<>();
        process(couponList, couponVOList);
        return Result.success(couponVOList);
    }

    /**
     * 根据id查询优惠券
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public Result<CouponVO> getById(@RequestParam Integer id){
        List<Coupon> couponList = couponService.selectById(id);
        List<CouponVO> couponVOList = new ArrayList<>();
        process(couponList, couponVOList);
        return Result.success(couponVOList.get(0));
    }


    private static void process(List<Coupon> couponList, List<CouponVO> couponVOList) {
        //处理查询结果
        for (Coupon coupon : couponList) {
            CouponVO couponVO = new CouponVO();
            couponVO.setId(coupon.getId());
            couponVO.setName(coupon.getName());
            couponVO.setCondition(coupon.getCondition());
            couponVO.setEndAt(LocalDateTime.ofInstant(Instant.ofEpochMilli(coupon.getEndAt()), ZoneOffset.of("+8")));
            couponVO.setStartAt(LocalDateTime.ofInstant(Instant.ofEpochMilli(coupon.getStartAt()), ZoneOffset.of("+8")));
            couponVO.setDescription(coupon.getDescription());
            couponVO.setValue(coupon.getValue());
            couponVO.setValueDesc(coupon.getValueDesc()+"折");
            couponVOList.add(couponVO);
        }
    }


}
